package com.qf.common.core.utils;

import org.springframework.core.LocalVariableTableParameterNameDiscoverer;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

public class SpelUtils {

    /**
     * 'stu'+#sid
     * 解析Spel表达式
     * @return
     */
    public static <T> T parse(String spel, Method method, Object[] paramValues, T defaultValue){

        //通过method对象，获取形参列表名称
        LocalVariableTableParameterNameDiscoverer parameterNameDiscoverer = new LocalVariableTableParameterNameDiscoverer();
        String[] parameterNames = parameterNameDiscoverer.getParameterNames(method);

        //创建一个表达式解析器
        ExpressionParser expressionParser = new SpelExpressionParser();

        //创建容器
        StandardEvaluationContext evaluationContext = new StandardEvaluationContext();
        //给容器设置相应的变量
        if (parameterNames != null && paramValues != null) {
            Map<String, Object> map = new HashMap<>();
            for (int i = 0; i < parameterNames.length; i++) {
                map.put(parameterNames[i], paramValues[i]);
            }
            evaluationContext.setVariables(map);
        }

        //解析表达式，获取解析器
        Expression expression = expressionParser.parseExpression(spel);
        //获取解析的结果
        try {
            return (T) expression.getValue(evaluationContext);
        } catch (Exception e) {
            return defaultValue;
        }
    }
}
